package com.zhongwang.business.module.quoteManage.quoteManageService;


import com.zhongwang.business.common.JsonResult;
import com.zhongwang.business.gen.entity.*;
import com.zhongwang.business.gen.mapper.*;
import com.zhongwang.business.module.basic.model.VerifyProcessModel;
import com.zhongwang.business.module.quoteManage.quoteManageDao.QuotationApproveDao;
import com.zhongwang.business.module.quoteManage.quoteManageDao.QuotationMainDao;
import com.zhongwang.business.module.quoteManage.quoteManageDao.QuotationQueryDao;
import com.zhongwang.business.module.quoteManage.quoteManageModel.QuotationMainModel;
import com.zhongwang.business.module.quoteManage.quoteManageModel.QuotationSublistModel;
import com.zhongwang.business.util.ShiroUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.zhongwang.business.module.system.log.LogService;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.jar.JarEntry;

/**
 *  报价查询服务层
 * @author zcy
 * @date 2020/11/2
 */
@Log4j2
@Service
public class QuoteQueryService {
    @Autowired
    private QuotationMainDao quotationMainDao;
    @Autowired
    private QuotationApproveDao quotationApproveDao;
    @Autowired
    private QuotationQueryDao quotationQueryDao;
    @Autowired
    private QuotationMainMapper quotationMainMapper;
    @Autowired
    private QuotationSublistMapper quotationSublistMapper;
    @Autowired
    private FileManageMapper fileManageMapper;
    @Autowired
    private TaskMapper taskMapper;
    @Autowired
    private VerifyProcessMapper verifyProcessMapper;
    @Autowired
    public LogService logService;

    @Value("${user.upload.path}")
    private String uploadPath;
    /**
     * 报价处理列表
     * @param query
     * @return
     */
    public List<QuotationMainModel> findQuotationQueryList(QuotationMainModel query) {
        List<QuotationMainModel> quotationMainModelList = quotationQueryDao.selectQuotationQueryList(query);
        int m = quotationMainModelList.size();
        for(int i = 0; i < m; i++){
            List<QuotationSublistModel> quotationSublistModelList = quotationQueryDao.selectQttProNameList(quotationMainModelList.get(i).getQuoteId());
            List<QuotationSublistModel> quotationSublistList = quotationQueryDao.selectComplTaskList(quotationMainModelList.get(i).getQuoteId());//有完结的报价
            String name = "";
            String code = "";
            for (int k= 0; k < quotationSublistModelList.size(); k++){
                name = name + quotationSublistModelList.get(k).getProName() + ",";
                code = code + quotationSublistModelList.get(k).getProCode() + ",";
            }
            quotationMainModelList.get(i).setProName(name);
            quotationMainModelList.get(i).setProCode(code);
            quotationMainModelList.get(i).setComplTaskQty(quotationSublistList.size());
        }
        return quotationMainModelList;
    }

    /**
     * 完结报价
     * @param quotationMainModel
     * @return
     */
    public JsonResult complQtt(QuotationMainModel quotationMainModel) {
        JsonResult jsonResult = new JsonResult();
        User user = ShiroUtils.getUser();
        try {
            List<Task> taskList = quotationQueryDao.selectTaskListByQuoteId(quotationMainModel.getQuoteId());
            if (taskList.size() != 0){
                for(Task task: taskList){
                    task.setTstatus(3);
                    task.setEnddate(new Date());
                    taskMapper.updateByPrimaryKeySelective(task);
                }
                quotationMainModel.setQuoteAvaStatus(2);
                quotationMainModel.setQttComplDate(new Date());
                quotationMainDao.updateQuote(quotationMainModel);
                quotationMainModel = quotationMainDao.selectQttInfo(quotationMainModel.getQuoteId());
                jsonResult.setType(JsonResult.ResultType.SUCCESS);
                jsonResult.setMsg("报价已完结！");
                logService.saveLog("报价完结","报价单号：【"+quotationMainModel.getQuoteNo()+"】【"+user.getName()+"】完结报价!");
            }else {
                jsonResult.setType(JsonResult.ResultType.ERROR);
                jsonResult.setMsg("报价完结失败！");
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            jsonResult.setType(JsonResult.ResultType.ERROR);
            jsonResult.setMsg("报价完结失败！");
        }
        return jsonResult;

    }

    /**
     * 反完结报价
     * @param quotationMainModel
     * @return
     */
    public JsonResult resetQtt(QuotationMainModel quotationMainModel) {
        JsonResult jsonResult = new JsonResult();
        User user = ShiroUtils.getUser();
        try {
            List<Task> taskList = quotationQueryDao.selectTaskListByQuoteId(quotationMainModel.getQuoteId());
            if (taskList.size() != 0){
                for(Task task: taskList){
                    task.setTstatus(2);
                    task.setEnddate(null);
                    quotationMainDao.updateTask(task);
                }
                quotationMainModel.setQuoteAvaStatus(1);
                quotationMainModel.setQttComplDate(null);
                quotationMainDao.updateResetQuote(quotationMainModel);
                quotationMainModel = quotationMainDao.selectQttInfo(quotationMainModel.getQuoteId());
                jsonResult.setType(JsonResult.ResultType.SUCCESS);
                jsonResult.setMsg("报价取消确认成功！");
                logService.saveLog("报价取消确认","报价单号：【"+quotationMainModel.getQuoteNo()+"】【"+user.getName()+"】报价单取消确认成功!");
            }else {
                jsonResult.setType(JsonResult.ResultType.ERROR);
                jsonResult.setMsg("报价取消确认失败！");
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            jsonResult.setType(JsonResult.ResultType.ERROR);
            jsonResult.setMsg("报价取消确认失败！");
        }
        return jsonResult;
    }

    /**
     * 存为历史版本时，如果报价任务状态为2执行中，则将当前报价单另存至历史版本并将报价主单状态置为报价人未提交状态
     *                 如果报价任务状态为3已完成，则将当前报价单另存至历史版本并将报价主单状态置为报价人未提交状态，并将任务状态置为2执行中
     * @param quotationMainModel
     * @return
     */
//    public int reQtt(QuotationMainModel quotationMainModel) {
//        if(quotationMainModel.getQuoteProcessStatus() == 2){
//            saveRevQtt(quotationMainModel);//插入历史版本报价单和报价明细
//            return restQtt(quotationMainModel);//重置报价单状态
//        }else if(quotationMainModel.getQuoteProcessStatus() == 3){
//            List<Task> taskList = quotationQueryDao.selectQttTaskListByQuoteId(quotationMainModel.getQuoteId());
//            if (taskList.size() != 0){
//                for(Task task: taskList){
//                    task.setTstatus(2);
//                    task.setEndDate(null);
//                    quotationQueryDao.updateTask(task);
//                }
//                saveRevQtt(quotationMainModel);//插入历史版本报价单和报价明细
//                return restQtt(quotationMainModel);//重置报价单状态
//            }else {
//                return 0;
//            }
//        }else {
//            return 0;
//        }
//    }

    /**
     * 根据当前报价单保存为历史版本报价主单和子单
     * @param quotationMainModel
     * @return
     */
//    private int saveRevQtt(QuotationMainModel quotationMainModel) {
//        QuotationMain quotationMainRev = quotationMainMapper.selectByPrimaryKey(quotationMainModel.getQuoteId());
//        List<QuotationSublist> quotationSublistListRev = quotationQueryDao.selectQttSubListByQuoteId(quotationMainModel.getQuoteId());
//        if (quotationSublistListRev.size() != 0){
//            quotationMainRev.setQuoteAvaStatus(2);
//            quotationMainRev.setQuoteRevNo(gentQuoteRevNo(quotationMainModel));
//            quotationMainRev.setQttPrtId(quotationMainModel.getQuoteId());
//            quotationMainRev.setQttRevDate(new Date());
//            quotationMainMapper.insertSelective(quotationMainRev);
//            for (QuotationSublist quotationSublist: quotationSublistListRev){
//                quotationSublist.setQuoteId(quotationMainRev.getQuoteId());
//                quotationSublistMapper.insertSelective(quotationSublist);
//            }
//            return 1;
//        }else return 0;
//    }

    /**
     * 生成历史报价单号
     * @param quotationMainModel
     * @return
     */
//    private String gentQuoteRevNo(QuotationMainModel quotationMainModel) {
//        List<QuotationMainModel> quoteRevNoList = quotationQueryDao.selectQuoteRevNoList(quotationMainModel);
//        String quoteRevNo;//历史报价单生成规则Rev001
//        if(quoteRevNoList.size() == 0) //如果没有报价单历史，则生成第一条
//        {
//            quoteRevNo = "Rev" + "001";
//        }else//如果已有历史报价单，则查找最后一个历史报价单号，按顺序生成下一个历史报价单号
//        {
//            quoteRevNo = "Rev" + String.format("%03d", Integer.parseInt(quoteRevNoList.get(quoteRevNoList.size()-1).getQuoteRevNo().substring(4, 6)) + 1);
//        }
//        return quoteRevNo;
//    }

    /**
     * 重新报价时，重置报价主单信息至报价人待提交状态
     * @param quotationMainModel
     * @return
     */
//    private int restQtt(QuotationMainModel quotationMainModel) {
//        QuotationMain quotationMain = new QuotationMain();
//        quotationMain.setQuoteId(quotationMainModel.getQuoteId());
//        quotationMain.setQuoteStatus(1);
//        quotationMain.setQuoteNo(gentQuoteNo());
//        quotationMain.setRevLastDate(new Date());
//        return quotationMainMapper.updateByPrimaryKeySelective(quotationMain);
//    }

    /**
     * 生成报价单号
     * @return 返回报价单号
     */
    private String gentQuoteNo() {
        // 取得当日零时时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        Date date = calendar.getTime();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String date1 = dateFormat.format(date);
        Date date2 = null;
        try {
            date2 = dateFormat.parse(date1);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        List<QuotationMainModel> quotationMainModel = quotationMainDao.selectQuoteNoList(date2); // 查询当月是否有报价单
        String quoteNo;//报价单生成规则202010100
        if(quotationMainModel.size() == 0) //如果当月没有报价单，则生成第一条
        {
            quoteNo = dateFormat.format(new Date()).substring(0,6) + "001";
        }else//如果已有报价单，则查找最后一个报价单号，按顺序生成下一个报价单号
        {
            quoteNo = dateFormat.format(new Date()).substring(0,6) + String.format("%03d", Integer.parseInt(quotationMainModel.get(quotationMainModel.size()-1).getQuoteNo().substring(7, 9)) + 1);
        }
        return quoteNo;
    }

    /**
     * 报价历史列表数据
     * @param query
     * @return
     */
//    public List<QuotationMainModel> findQttHistoryList(QuotationMainModel query) {
//        List<QuotationMainModel> quotationMainModel = quotationQueryDao.selectQttHistoryList(query);
//        return quotationMainModel;
//    }

    /**
     * 报价查询列表
     * @param query
     * @return
     */
    public List<QuotationMainModel> findQuoteSearchlist(QuotationMainModel query) {
        List<QuotationMainModel> quotationMainModelList = quotationQueryDao.selectQuoteSearchlist(query);
        int m = quotationMainModelList.size();
        for(int i = 0; i < m; i++){
            List<QuotationSublistModel> quotationSublistModelList = quotationQueryDao.selectQttProNameList(quotationMainModelList.get(i).getQuoteId());
            String name = "";
            String code = "";
            for (int k= 0; k < quotationSublistModelList.size(); k++){
                name = name + quotationSublistModelList.get(k).getProName() + ",";
                code = code + quotationSublistModelList.get(k).getProCode() + ",";
            }
            quotationMainModelList.get(i).setProName(name);
            quotationMainModelList.get(i).setProCode(code);
        }
        return quotationMainModelList;
    }
}
